package com.zixun.controller;

import com.zixun.config.JsonTools;
import com.zixun.config.WebApiConfig;
import com.zixun.model.Agent;
import com.zixun.repository.AgentRepository;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Basil on 16/8/13.
 */
@RestController
@Transactional
@RequestMapping("/api/agent")
public class AgentWebApi{

    @Autowired
    AgentRepository agentRepository;
    /**
     * @api {POST} /api/agent/applyAgent 申请代理
     * @apiName applyAgent
     * @apiGroup agent
     * @apiVersion 0.0.1
     * @apiDescription 申请代理
     * @apiParamExample 请求参数{JSON}
     * {
     * "sex":【用户性别 0:女 1:男, 整型 】,
     * "name":【姓名，字符串】,
     * "mobilephone":【联系方式，字符串】
     * }
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功,2:参数错误,3:服务器异常,19:手机号码格式不正确, 整型】,
     * "errMsg":【错误信息 , 字符串】,
     * }
     */
    @RequestMapping("applyAgent")
    public Object applyAgent(@RequestBody String data){
        Map result = new HashMap();
        try {
            Agent agent = JsonTools.fromJson(data,Agent.class);
            System.out.println("mobilephone:"+agent.getMobilephone());
            System.out.println("name:"+agent.getName());
            System.out.println("sex:"+agent.getSex());
            if(agent==null||agent.getMobilephone()==null||agent.getSex()==null||agent.getName()==null||(agent.getSex()!=1&&agent.getSex()!=0)) {
                result.put("errMsg","参数错误");
                result.put("returnValue",2);
                return  result;
            }
            if(!Pattern.matches(WebApiConfig.REGEX_MOBILE, agent.getMobilephone())){
                result.put("errMsg","手机号码格式不正确");
                result.put("returnValue",19);
                return result;
            }
            agent.setCreateTime(new Date(System.currentTimeMillis()));
            agentRepository.save(agent);
            result.put("errMsg", "成功");
            result.put("returnValue",1);
            return result;
        }catch (JSONException e){
            e.printStackTrace();
            result.put("errMsg","JSON参数异常");
            result.put("returnValue",11);
            return result;
        }
        catch (Exception e) {
            e.printStackTrace();
            result.put("errMsg","服务器异常");
            result.put("returnValue",3);
            return result;
        }
    }
}
